<template>

  <div class="table1_container">
    <div class="table1_dataShower" style="padding-bottom: 50px; padding-top: 50px; box-sizing: border-box">
      <button class="report-top-button" @click="back">返回上级页面</button>

      <button class="report-top-button" @click="openFieldDialog">选择字段</button>
      <button class="report-top-button" @click="printReport">报表打印</button>
      <div style="text-align: center; margin: 10px 0;">
        <div style="display: inline-flex; gap: 20px;">
          <!-- 未完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffffff; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>未完成</span>
          </div>

          <!-- 已完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #e6f7e6; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>已完成</span>
          </div>

          <!-- 不合格重采 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffebeb; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>不合格重采</span>
          </div>
        </div>
      </div>
      <h1>混凝土、砂浆试块(同养、标养)试验报告汇总表</h1>
      <!-- 基本信息部分 - 在表格上方 -->
      <div style="width:90%;margin:0 auto;display: flex">
        <div style="text-align: left">
          <span>工程名称:</span>
          <span>{{ projectName + '  ' + subprojectName }}</span>
        </div>
        <div style="margin-left: 50em;letter-spacing: 2em">
          <span>年月日</span>
        </div>
      </div>
      <table class="wendu-table1_top_table">
        <!-- 表头第一行 -->
        <tr>
          <template v-for="field in tableHeaders">
            <template v-if="field.type === 'dateGroup'">
              <td :key="field.key" rowspan="1" :colspan="field.colspan">日期</td>
            </template>
            <template v-else-if="field.type === 'chipGroup'">
              <td :key="field.key" rowspan="2" :colspan="field.colspan">芯片编号</td>
            </template>
            <template v-else>
              <td :key="field.key" rowspan="2">{{ field.label }}</td>
            </template>
          </template>
        </tr>
        <!-- 表头第二行 -->
        <tr>
          <template v-for="field in tableHeaders">
            <template v-if="field.type === 'dateGroup'">
              <td v-if="isFieldVisible('witnessDate')" :key="'witnessDate-header'">成型</td>
              <td v-if="isFieldVisible('checkDate')" :key="'checkDate-header'">收样</td>
              <td v-if="isFieldVisible('reportDate')" :key="'reportDate-header'">试压</td>
            </template>
            <template v-else-if="field.type === 'chipGroup'">
              <!-- 芯片编号没有子表头 -->
            </template>
          </template>
        </tr>
        <!-- 数据行 -->
        <tr v-for="(item, index) in reportData" :key="index">
          <template v-for="field in tableHeaders">
            <template v-if="field.type === 'dateGroup'">
              <td v-if="isFieldVisible('witnessDate')" :key="'witnessDate-' + index">{{ item.witnessDate }}</td>
              <td v-if="isFieldVisible('checkDate')" :key="'checkDate-' + index">{{ item.checkDate }}</td>
              <td v-if="isFieldVisible('reportDate')" :key="'reportDate-' + index">{{ item.reportDate }}</td>
            </template>
            <template v-else-if="field.type === 'chipGroup'">
              <td v-if="isFieldVisible('chipNumber1')" :key="'chipNumber1-' + index">
                {{ item.chipNumbers && item.chipNumbers[0] }}
              </td>
              <td v-if="isFieldVisible('chipNumber2')" :key="'chipNumber2-' + index">
                {{ item.chipNumbers && item.chipNumbers[1] }}
              </td>
              <td v-if="isFieldVisible('chipNumber3')" :key="'chipNumber3-' + index">
                {{ item.chipNumbers && item.chipNumbers[2] }}
              </td>
            </template>
            <template v-else>
              <td :key="field.key + '-' + index">{{ getFieldValue(item, field.key, index) }}</td>
            </template>
          </template>
        </tr>
        <!-- 说明行 -->
        <tr>
          <td :colspan="totalColumns" style="text-align: left">
            说明：在检验不合格后又重新取样检验合格的，两次检验结果都必须统计在汇总表中。
          </td>
        </tr>
        <!--        <tr>-->
        <!--          <td colspan="7" style="text-align: left;border-width: 0">施工单位项目技术负责人：{{ 'XXX' }}</td>-->
        <!--          <td colspan="10" style="text-align: left">总监理工程师(建设单位项目技术负责人)：{{ 'XXX' }}</td>-->
        <!--          <td colspan="8" style="text-align: left">（监理项目部章）</td>-->
        <!--          <td colspan="21" style="text-align: left">填表人：{{ 'XXX' }}</td>-->
        <!--        </tr>-->
      </table>
      <div class="report-footer-info" style="text-align: left; width: 90%;margin: 0 auto;display: flex">
        <div>施工单位项目技术负责人：</div>
        <div style="margin-left: 10%">总监理工程师(建设单位项目技术负责人)：</div>
        <div style="margin-left: 10%">（监理项目部章）</div>
        <div style="margin-left: 10%">填表人：</div>
      </div>
    </div>

    <!-- 字段选择对话框 -->
    <el-dialog
      title="选择显示字段"
      :visible.sync="fieldDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <div style="max-height: 500px; overflow-y: auto;">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          style="margin-bottom: 15px;"
        >
          全选
        </el-checkbox>
        <el-divider></el-divider>
        <el-checkbox-group
          v-model="selectedFields"
          @change="handleCheckedFieldsChange"
          class="field-checkbox-group"
        >
          <div
            v-for="field in allFields"
            :key="field.key"
            style="margin-bottom: 10px; text-align: left;"
          >
            <el-checkbox :label="field.key">{{ field.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmFieldSelection">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

/*
 *    这个报表真麻烦！！！
 *
 */

import { searchLedgerPreview } from '@/api/statementManage/hunNingTu/hunNingTu'

export default {
  data() {
    return {
      localStorageId: '',
      reportData: {},
      previewData: {},
      projectName: '',
      subprojectName: '',
      // 字段选择相关
      fieldDialogVisible: false,
      checkAll: true,
      isIndeterminate: false,
      selectedFields: [], // 选中的字段key数组
      allFields: [ // 所有可用字段
        { key: 'dataId', label: '批次' },
        { key: 'usePart', label: '试块部位及构件名称' },
        { key: 'concreteType', label: '砂浆种类' },
        { key: 'concreteStrength', label: '强度等级' },
        { key: 'maintCondition', label: '试块养护条件' },
        { key: 'representAmount', label: '代表数量' },
        { key: 'witnessDate', label: '日期-成型' },
        { key: 'checkDate', label: '日期-收样' },
        { key: 'reportDate', label: '日期-试压' },
        { key: 'concreteAge', label: '龄期（d）' },
        { key: 'reportNumber', label: '报告编号' },
        { key: 'representStrength', label: '强度代表值（MPa）' },
        { key: 'designedRatio', label: '达到设计强度等级（%）' },
        { key: 'projectName', label: '项目名称' },
        { key: 'producer', label: '生产厂家' },
        { key: 'conclusion', label: '检验结果' },
        { key: 'subprojectName', label: '单位工程' },
        { key: 'primaryKey', label: '主键' },
        { key: 'yanshouRule', label: '验收规范' },
        { key: 'projectNumber', label: '工程号' },
        { key: 'superviseNumber', label: '监督号' },
        { key: 'checkCompany', label: '检测单位' },
        { key: 'delegateCompany', label: '委托单位' },
        { key: 'delegateNumber', label: '委托编号' },
        { key: 'witnessCompany', label: '见证单位' },
        { key: 'witnessPerson', label: '见证人' },
        { key: 'sendPerson', label: '送样人' },
        { key: 'checkType', label: '检验类别' },
        { key: 'jiansheCompany', label: '建设单位' },
        { key: 'shigongCompany', label: '施工单位' },
        { key: 'chipNumber1', label: '芯片编号1' },
        { key: 'chipNumber2', label: '芯片编号2' },
        { key: 'chipNumber3', label: '芯片编号3' },
        { key: 'concreteVolume', label: '试块规格' }
      ]
    }
  },
  computed: {
    // 生成表头结构
    tableHeaders() {
      const headers = []
      const dateFields = ['witnessDate', 'checkDate', 'reportDate']
      const chipFields = ['chipNumber1', 'chipNumber2', 'chipNumber3']
      const selectedDateFields = this.selectedFields.filter(k => dateFields.includes(k))
      const selectedChipFields = this.selectedFields.filter(k => chipFields.includes(k))

      // 按原始顺序遍历所有字段
      let dateGroupAdded = false
      let chipGroupAdded = false

      this.allFields.forEach(field => {
        if (this.selectedFields.includes(field.key)) {
          // 处理日期组合字段
          if (dateFields.includes(field.key)) {
            if (!dateGroupAdded) {
              headers.push({
                key: 'dateGroup',
                type: 'dateGroup',
                label: '日期',
                colspan: selectedDateFields.length
              })
              dateGroupAdded = true
            }
          }
          // 处理芯片编号组合字段
          else if (chipFields.includes(field.key)) {
            if (!chipGroupAdded) {
              headers.push({
                key: 'chipGroup',
                type: 'chipGroup',
                label: '芯片编号',
                colspan: selectedChipFields.length
              })
              chipGroupAdded = true
            }
          }
          // 普通字段
          else {
            headers.push({
              key: field.key,
              type: 'normal',
              label: field.label
            })
          }
        }
      })

      return headers
    },
    // 计算总列数（用于说明行的colspan）
    totalColumns() {
      const dateFields = ['witnessDate', 'checkDate', 'reportDate']
      const chipFields = ['chipNumber1', 'chipNumber2', 'chipNumber3']
      const dateCount = this.selectedFields.filter(k => dateFields.includes(k)).length
      const chipCount = this.selectedFields.filter(k => chipFields.includes(k)).length
      const normalCount = this.selectedFields.length - dateCount - chipCount
      // 总列数 = 普通字段数 + 日期实际列数 + 芯片实际列数
      return normalCount + dateCount + chipCount
    }
  },
  async mounted() { // 钩子函数

    const sessionData = sessionStorage.getItem('tempObj1')

    const parseData = JSON.parse(sessionData)
    this.projectName = parseData.projectName
    this.subprojectName = parseData.subprojectName
    const subprojectId = parseData.subprojectId

    const { result } = await searchLedgerPreview(subprojectId, '标准养护')

    this.reportData = result
    console.log(JSON.stringify(result))

    // 初始化字段选择（默认全选）
    this.selectedFields = this.allFields.map(f => f.key)
    this.checkAll = true
    this.isIndeterminate = false

    // // 赶紧从接口拿数据
    // try {
    //   const { result } = await searchInpsectCheckPreview(this.reportData.taskId)
    //   console.log(result)
    //   this.previewData = result
    //   console.log(this.previewData)
    //   this.$message.success('报表已生成！')
    // } catch (err) {
    //   this.$message.error('报表生成失败！')
    // }
  },
  beforeDestroy() { // 离开页面要做的事
    // 那就是清除localstorage！！！
    if (this.localStorageId) {
      localStorage.removeItem(this.localStorageId)
    }
    document.querySelector('body').setAttribute('style', 'background-color: white;') // 还原，因为这是个全局样式
  },
  beforeCreate() {
    document.querySelector('body').setAttribute('style', 'background-color:#f5f5f5;') // 设置对比色
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    // 打开字段选择对话框
    openFieldDialog() {
      this.fieldDialogVisible = true
    },
    // 全选/取消全选
    handleCheckAllChange(val) {
      this.selectedFields = val ? this.allFields.map(f => f.key) : []
      this.isIndeterminate = false
    },
    // 字段选择变化时更新全选状态
    handleCheckedFieldsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.allFields.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allFields.length
    },
    // 确认字段选择
    confirmFieldSelection() {
      if (this.selectedFields.length === 0) {
        this.$message.warning('请至少选择一个字段！')
        return
      }
      this.fieldDialogVisible = false
      this.$message.success('字段选择已更新！')
    },
    // 打印报表
    printReport() {
      window.print()
    },
    // 判断字段是否可见（用于日期和芯片编号的子字段显示）
    isFieldVisible(fieldKey) {
      return this.selectedFields.includes(fieldKey)
    },
    // 根据字段key获取对应的值
    getFieldValue(item, fieldKey, index) {
      const valueMap = {
        'dataId': item.dataId,
        'usePart': item.usePart,
        'concreteType': item.concreteType,
        'concreteStrength': item.concreteStrength,
        'maintCondition': item.maintCondition,
        'representAmount': item.representAmount,
        'concreteAge': item.concreteAge,
        'reportNumber': item.reportNumber,
        'representStrength': item.representStrength,
        'designedRatio': item.designedRatio,
        'projectName': this.projectName,
        'producer': item.producer,
        'conclusion': item.conclusion,
        'subprojectName': this.subprojectName,
        'primaryKey': index,
        'yanshouRule': item.yanshouRule,
        'projectNumber': item.projectNumber,
        'superviseNumber': item.superviseNumber,
        'checkCompany': item.checkCompany,
        'delegateCompany': item.delegateCompany,
        'delegateNumber': item.delegateNumber,
        'witnessCompany': item.witnessCompany,
        'witnessPerson': item.witnessPerson,
        'sendPerson': item.sendPerson,
        'checkType': item.checkType,
        'jiansheCompany': item.jiansheCompany,
        'shigongCompany': item.shigongCompany,
        'concreteVolume': item.concreteVolume
      }
      return valueMap[fieldKey] || ''
    }
  }
}
</script>

<style>

@media print {

  .table1_container {
    width: 100% !important;
    margin: 0 0 !important;
    font-size: 13px !important;
  }

  .table1_dataShower {
    width: 100% !important;
    margin: 0 0 !important;
    padding: 5px !important;
    border: none !important;
    font-size: 10px !important;
  }

  .report-top-button {
    display: none !important;
  }

  .table1_dataShower div {
    display: none !important;
  }

  .table1_dataShower .report-footer-info {
    display: flex !important;
  }

  .table1_dataShower .report-footer-info div {
    display: block !important;
  }

  .wendu-table1_top_table tr td {
    height: 40px !important;
    font-size: 7px !important;
  }

  @page {
    size: A4 landscape; /* A4纸横向 */
    margin-top: 20px;
    margin-bottom: 20px;
  }

}

/*
先来设置每个任务项对应的背景颜色吧！
 */
.row-unfinished {
  background-color: #ffffff; /* 未完成 - 白色或默认色 */
}

.row-finished {
  background-color: #e6f7e6; /* 已完成 - 浅绿色 */
}

.row-failed {
  background-color: #ffebeb; /* 不合格重采 - 浅红色 */
}

.table1_container {
  width: 4500px;
  background: white;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding-bottom: 20px;
}

.table1_dataShower {
  width: 80%;
  background: white;
  margin: 0 auto;
  border: 2px black solid;
}

/*这是返回按钮的样式*/
.report-top-button {
  display: block;
  margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
  color: #ffffff;
  background: linear-gradient(90deg, #1e3a8a, #3b82f6); /* 建筑行业蓝色调，稳重且有活力 */
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.report-top-button:hover {
  background: linear-gradient(90deg, #1e3a8a, #2563eb);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.report-top-button:active {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
}

.field-checkbox-group {
  text-align: left;
}

.field-checkbox-group .el-checkbox {
  width: 100%;
}

/*表格样式*/
.wendu-table1_top_table {
  width: 90%;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid black;
  table-layout: fixed;
}

/*表格的样式*/
.wendu-table1_top_table tr td {
  height: 50px;
  border: 1px solid black;
  word-wrap: break-word; /* 允许长单词换行 */
  overflow-wrap: break-word; /* 更现代的换行属性 */
}

#table1_top_table_last_col {
  width: 20%;
  min-height: 50px;
}

th {
  box-sizing: border-box !important;
}
</style>

